package com.mybatisplus.controller;

import com.mybatisplus.entity.BaseResultBean;
import com.mybatisplus.service.SendEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Random;

/**
 * Auto created By IntelliJ IDEA
 *
 * @author : gzrong
 * @Date : 2023/4/2213:41
 */
@RestController
@RequestMapping("/SendEmail")
public class EmailController {
    @Autowired
    private SendEmailService sendEmailService;

    @RequestMapping("sendCode")
    public BaseResultBean sendCode(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Long sendTime = new Date().getTime();
        BaseResultBean bean = new BaseResultBean();
        int code = new Random().nextInt(8999) + 1000;
        try {
            sendEmailService.sendEmail(request.getParameter("targetEmail"), "您正在修改密码", "我们收到了你的验证码请求；你的邮箱验证码为" + code + "\n验证码五分钟内有效！");
            session.setAttribute("code", code);
            session.setAttribute("sendTime", sendTime);
            bean.setMessage("验证码已发送，5分钟内有效");
            bean.setStatus(true);
        } catch (MessagingException e) {
            bean.setMessage("验证码发送失败，请重试！");
            bean.setStatus(false);
        }
        return bean;
    }

    @RequestMapping("verifyCode")
    public BaseResultBean verifyCode(HttpServletRequest request) {
        long receiveTime = new Date().getTime();
        BaseResultBean bean = new BaseResultBean();
        final HttpSession session = request.getSession(false);
        final String code = String.valueOf(session.getAttribute("code"));
        if (receiveTime - new Date().getTime() < 5 * 60 * 1000) {
            if (code.equals(request.getParameter("code"))) {
                bean.setMessage("验证通过!");
                bean.setStatus(true);
                session.removeAttribute("code");
            } else {
                bean.setMessage("验证码错误,请重试!");
                bean.setStatus(false);
            }
        } else {
            bean.setStatus(false);
            bean.setMessage("验证码已过期,请重新发送验证码!");
        }
        return bean;
    }
}
